using System;
using KJFramework.Dynamic.Contracts;
using KJFramework.IO.Helper;
using KJFramework.Logger;
using KJFramework.Platform.Deploy.CSN.CP.Connector.Subscribers;
using KJFramework.Platform.Deploy.CSN.CP.Connector.Transmitters;
using KJFramework.Platform.Deploy.CSN.CP.Connector.Transmitters.Contexts;
using KJFramework.Platform.Deploy.CSN.ProtocolStack;
using KJFramework.Platform.Deploy.CSN.ProtocolStack.Enums;

namespace KJFramework.Platform.Deploy.CSN.CP.Connector.Contracts
{
    internal class ComponentTunnelService : IComponentTunnelContract
    {
        #region Implementation of IComponentTunnelContract

        public void Transport(object obj)
        {
            try
            {
                CSNMessage message = (CSNMessage)obj;
                IConfigSubscriber subscriber = ConfigSubscriberManager.GetSubscriber(message.Header.ServiceKey);
                if (subscriber == null)
                {
                    string alterInfo = "#Can not send a response message to dynamic service, because that subscriber no existed. #Key: " + message.Header.ServiceKey;
                    ConsoleHelper.PrintLine(alterInfo, ConsoleColor.DarkYellow);
                    Logs.Logger.Log(alterInfo);
                    return;
                }
                message.Bind();
                if (!message.IsBind)
                {
                    string alterInfo = "#Can not send a response message to dynamic service, because IntellectObject.IsBind property is false. #Key: " + message.Header.ServiceKey;
                    ConsoleHelper.PrintLine(alterInfo, ConsoleColor.DarkYellow);
                    Logs.Logger.Log(alterInfo);
                    return;
                }
                #region configuration transmitter assembled.

                ITransmitterContext transmitterContext = new TransmitterContext();
                transmitterContext.PreviousSessionId = message.Header.SessionId;
                transmitterContext.ResponseMessage = message;
                transmitterContext.ConfigType = message is CSNGetDataTableResponseMessage
                                                    ? ConfigTypes.Table
                                                    : ConfigTypes.KeyData;
                transmitterContext.Subscriber = subscriber;
                IConfigTransmitter configTransmitter = new ConfigTransmitter(subscriber, transmitterContext);
                configTransmitter.Next();

                #endregion
            }
            catch (System.Exception ex)
            {
                Logs.Logger.Log(ex);
            }
        }

        #endregion
    }
}